<?php
/**
 * User: Small Y
 * Date: 2019/04/16.
 */

namespace app\api\service;

use app\common\service\CommonService;
use app\models\AllocationCampusModel;
use app\models\AllocationOnlyModel;
use app\models\ContractModel;
use app\models\CourseContractModel;
use app\models\CourseLogModel;
use app\models\GoodsContractModel;
use app\models\GradesContractModel;
use app\models\ParentInformationModel;
use app\models\ReceivablesModel;
use app\models\RefundAmountModel;
use app\models\StudentModel;
use app\models\StudentSubjectInfosClassModel;
use app\models\UserModel;
use think\Db;
use think\Log;

class NotifyService
{
    /**
     * 随行付支付回调通知
     * User: wufeng
     * Date: 2019/4/11.
     *
     * @throws \think\exception\DbException
     *
     * @return bool|string
     */
    public function sxfNotify()
    {
        $res = file_get_contents('php://input');
        Log::record('回调时间===='.date('Y-m-d H:i:s').'原始信息='.$res, 'notify');
        $data = json_decode($res, true);
        Log::record('支付单号===='.$data['ordNo'], 'notify');
        $receivables = ReceivablesModel::get(['receipt_number' => $data['ordNo']]);
        Log::record('开始===='.json_encode($receivables), 'notify');
        if ('1' == $receivables['status']) {
            Db::startTrans();
            Log::record('事务启动', 'notify');

            try {
                //缴费通过
                $contractModel = ContractModel::get(['contract_number' => $receivables['contract_number']]);
                ReceivablesModel::where(['receipt_number' => $receivables['receipt_number']])->update(['status' => 2]);
                Log::record('缴费通过', 'notify');

                $data['amount'] = $data['amt'] * 100; //已收款金额

                // 财务流程
                //应收【total_amount】  课程收费【amount】  实收【net_receipts】   欠费【stay_amount】    支出【expenditure】   余额【balance】    储值【Storedvalue】
                $total_amount_money = $contractModel['total_amount']; //应收
                $amount_money = $contractModel['amount'] + $data['amount']; //课程收费
                $storedvalue = 0;
                $net_receipts = 0;
                $des_storedvalue = 0;
                if ($amount_money <= $total_amount_money) {
                    $storedvalue = 0;   //储值
                    $net_receipts = $amount_money;
                } elseif ($amount_money > $total_amount_money) {
                    $des_storedvalue = ($amount_money - $total_amount_money); //储蓄增量
                    $storedvalue = ($amount_money - $total_amount_money) + $contractModel['storedvalue'];
                    $net_receipts = $amount_money;
                    $amount_money = $total_amount_money;
                }
                $stay_amount_money = ($total_amount_money - $amount_money);  //欠费
                $expenditure_money = $contractModel['expenditure']; //支出[课消]
                $balance_money = ($amount_money - $expenditure_money);  //余额
                // END

                    $courses = explode(',', $contractModel['course']);
                //获取课程单价，需从课程和订单关系表获得,收款默认充值到第一个课程上面
                $price_result = CourseContractModel::get(['course_id' => $courses[0], 'contract_id' => $contractModel['id'], 'campus_id' => $contractModel['campus_id']]);
                $price = $price_result['price'];
                $real_rate = ($contractModel['real_rate'] / 100); //真实的折扣率
                if ($price > 0) {
                    $course_paid_nums = round(($data['amount'] / ($price * $real_rate)), 2);
                } else {
                    $course_paid_nums = 0;
                }
                $course_paid_nums_old = $contractModel['course_paid_nums'];  //原订单实缴课节数
                $course_paid_nums_old_arr = explode(',', $course_paid_nums_old);
                $arr_new = '';
                for ($i = 0; $i < \count($course_paid_nums_old_arr); ++$i) {
                    if (0 === $i) {
                        $course_paid_nums_old_arr[$i] = $course_paid_nums_old_arr[$i] + $course_paid_nums;
                    }
                    $arr_new = $arr_new.$course_paid_nums_old_arr[$i].',';
                }
                $arr_new = substr($arr_new, 0, \strlen($arr_new) - 1);
                $contract_data['course_paid_nums'] = $arr_new; //实收课时

                $contract_data['stay_amount'] = $stay_amount_money; //欠费
                $contract_data['amount'] = $amount_money;  //课程收费
                $contract_data['net_receipts'] = $net_receipts;  //实际收费
                $contract_data['total_amount'] = $total_amount_money;  //应收
                $contract_data['expenditure'] = $expenditure_money;  //课消
                $contract_data['balance'] = $balance_money;  //余额
                $contract_data['storedvalue'] = $storedvalue;  //储值

                //更新学生储蓄账户
                $student_result = StudentModel::get(['id' => $contractModel['student_id']]);
                //更新欠费状态
                if ($contract_data['balance'] >= 0) {
                    StudentModel::where(['id' => $contractModel['student_id']])->update(['arrears_status' => 1]);
                } elseif ($contract_data['balance'] < 0) {
                    StudentModel::where(['id' => $contractModel['student_id']])->update(['arrears_status' => 0]);
                }
                Log::record('更新欠费状态', 'notify');
				$contract_data['id'] = $contractModel['id'];  //储值
				ContractModel::update($contract_data);
				Log::record('更新订单代收款金额', 'notify');
                $srudent_item['storedvalue'] = $student_result['storedvalue'] + $des_storedvalue;
                StudentModel::update(['storedvalue' => $srudent_item['storedvalue'], 'id' => $contractModel['student_id']]);
                Log::record('更新学生储蓄账户', 'notify');
                if ($contract_data['stay_amount'] > 0) {
                    $contract_data['status'] = 3; //订单状态：部分收款订单
                } else {
                    $contract_data['status'] = 1; //订单状态：已收款订单
                }
                // 更新已报课程状态
                CourseLogModel::where(['contract_number' => $contractModel['contract_number']])->update(['status' => $contract_data['status']]);
                Log::record('更新已报课程状态', 'notify');
                // 订单收款流水
				$operator = UserModel::get($receivables['payee'])['name'];
                CommonService::writeFlowRecord($contractModel['contract_number'],$operator, 1, $data['amount'], '记录订单收款流水', $receivables['campus_id'], $receivables['receipt_number']);
                Log::record('写入订单收款流水', 'notify');
                Db::commit(); // 提交事务
                Log::record('事务提交-done', 'notify');
            } catch (\Exception $e) {
                Db::rollback();
                Log::record('报错'.json_encode($e->getMessage()), 'notify');
                $errorMsg = $e->getMessage().' 在 '.$e->getFile().' '.$e->getLine().' 行'.$e->getTraceAsString();
                Log::error($errorMsg);

                return false;
            }

            return 'success';
        }
        if ('2' == $receivables['status']) {
            Log::record('订单'.$receivables['receipt_number'].'已经回调过了', 'notify');
        }
        Log::record('回调失败===='.json_encode($receivables), 'notify');

        return false;
    }

    /**
     * 随行付退款回调通知
     * User: wufeng
     * Date: 2019/4/11.
     *
     * @throws \think\exception\DbException
     *
     * @return bool|string
     */
    public function refundNotify()
    {
        $res = file_get_contents('php://input');
        Log::record('回调时间===='.date('Y-m-d H:i:s').'原始信息='.$res, 'notify');
        $data = json_decode($res, true);
        Log::record('支付单号===='.$data['ordNo'], 'notify');
        $refundAmount = RefundAmountModel::get(['receipt_number' => $data['ordNo']]);
        Log::record('开始===='.json_encode($refundAmount), 'notify');
        if ('0' == $refundAmount['refund_status']) {
            Db::startTrans();
            Log::record('事务启动', 'notify');

            try {
                ReceivablesModel::where(['id' => $refundAmount['receivables_id']])->update(['status' => 3]);
				Log::record('更新收款表状态:已退款', 'notify');
                RefundAmountModel::where(['receipt_number' => $refundAmount['receipt_number']])->update(['refund_status' => 1]);
                Log::record('更新退款状态', 'notify');
				$contractModel = ContractModel::get(['contract_number' => $refundAmount['contract_number']]);
                $updateData = array(
					'balance' => $refundAmount['balance'],//余额更新
					'net_receipts' => $contractModel['net_receipts'] - $refundAmount['amount'],//实际收款更新
					'amount' => $contractModel['amount'] - $refundAmount['amount'],//课程收费更新
					'stay_amount' => $contractModel['stay_amount'] + $refundAmount['amount'],//欠费更新
				);
                ContractModel::where(['contract_number' => $refundAmount['contract_number']])->update($updateData);
                Log::record('更新订单账户余额', 'notify');

                //退费流水
				$operator = UserModel::get($refundAmount['experienced_person'])['name'];
                CommonService::writeFlowRecord($refundAmount['contract_number'], $operator,2, $refundAmount['refund_amount'], '记录订单退款流水', $refundAmount['campus_id'], $refundAmount['receipt_number']);
                Log::record('写入订单退款流水', 'notify');
                Db::commit(); // 提交事务
                Log::record('事务提交-done', 'notify');
            } catch (\Exception $e) {
                Db::rollback();
                Log::record('报错'.json_encode($e->getMessage()), 'notify');
                $errorMsg = $e->getMessage().' 在 '.$e->getFile().' '.$e->getLine().' 行'.$e->getTraceAsString();
                Log::error($errorMsg);

                return false;
            }

            return 'success';
        }
        if ('1' == $refundAmount['status']) {
            Log::record('订单'.$refundAmount['receipt_number'].'已经回调过了', 'notify');
        }
        Log::record('回调失败===='.json_encode($refundAmount), 'notify');

        return false;
    }

	/**
	 * 微信扫码支付回调-储值后台
	 * User: wufeng
	 * Date: 2020/04/16
	 *
	 * @return bool|string
	 * @throws \think\exception\DbException
	 */
	public function czwxsmNotify()
	{
		$result = file_get_contents('php://input');
		Log::record('微信回调,时间'.date('Y-m-d H:i:s').'原始信息='.$result, 'notify');
		$values = json_decode(json_encode(simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		Log::record('微信回调信息===='.json_encode($values), 'notify');

		Log::record('支付单号===='.$values['out_trade_no'], 'notify');
		$receivables = ReceivablesModel::get(['receipt_number' => $values['out_trade_no']]);
		Log::record('开始===='.json_encode($receivables), 'notify');
		if ('1' == $receivables['status']) {
			Db::startTrans();
			Log::record('事务启动', 'notify');

			try {
				$this->callbackUpdate($receivables,$values,1);
				Db::commit(); // 提交事务
				Log::record('事务提交-done', 'notify');
			} catch (\Exception $e) {
				Db::rollback();
				Log::record('报错'.json_encode($e->getMessage()), 'notify');
				$errorMsg = $e->getMessage().' 在 '.$e->getFile().' '.$e->getLine().' 行'.$e->getTraceAsString();
				Log::error($errorMsg);

				return false;
			}

			return 'success';
		}
		if ('2' == $receivables['status']) {
			Log::record('订单'.$receivables['receipt_number'].'已经回调过了', 'notify');
		}
		Log::record('回调失败===='.json_encode($receivables), 'notify');

		return false;
	}

	/**
	 * 微信扫码支付回调-订单后台
	 * User: wufeng
	 * Date: 2020/04/25
	 *
	 * @return bool|string
	 * @throws \think\exception\DbException
	 */
	public function ddwxsmNotify()
	{
		$result = file_get_contents('php://input');
		Log::record('微信回调,时间'.date('Y-m-d H:i:s').'原始信息='.$result, 'notify');
		$values = json_decode(json_encode(simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		Log::record('微信回调信息===='.json_encode($values), 'notify');

		Log::record('支付单号===='.$values['out_trade_no'], 'notify');
		$receivables = ReceivablesModel::get(['receipt_number' => $values['out_trade_no']]);
		Log::record('开始===='.json_encode($receivables), 'notify');
		if ('1' == $receivables['status']) {
			Db::startTrans();
			Log::record('事务启动', 'notify');

			try {
				$this->callbackUpdate($receivables,$values,2);
				Db::commit(); // 提交事务
				Log::record('事务提交-done', 'notify');
			} catch (\Exception $e) {
				Db::rollback();
				Log::record('报错'.json_encode($e->getMessage()), 'notify');
				$errorMsg = $e->getMessage().' 在 '.$e->getFile().' '.$e->getLine().' 行'.$e->getTraceAsString();
				Log::error($errorMsg);

				return false;
			}

			return 'success';
		}
		if ('2' == $receivables['status']) {
			Log::record('订单'.$receivables['receipt_number'].'已经回调过了', 'notify');
		}
		Log::record('回调失败===='.json_encode($receivables), 'notify');

		return false;
	}

	/**
	 * 微信小程序扫码支付回调-储值
	 * User: wufeng
	 * Date: 2020/04/25
	 *
	 * @return bool|string
	 * @throws \think\exception\DbException
	 */
	public function czxcxsmNotify()
	{
		$result = file_get_contents('php://input');
		Log::record('微信回调,时间'.date('Y-m-d H:i:s').'原始信息='.$result, 'notify');
		$values = json_decode(json_encode(simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		Log::record('微信回调信息===='.json_encode($values), 'notify');

		Log::record('支付单号===='.$values['out_trade_no'], 'notify');
		$receivables = ReceivablesModel::get(['receipt_number' => $values['out_trade_no']]);
		Log::record('开始===='.json_encode($receivables), 'notify');
		if ('1' == $receivables['status']) {
			Db::startTrans();
			Log::record('事务启动', 'notify');

			try {
				$this->callbackUpdate($receivables,$values,3);
				Db::commit(); // 提交事务
				Log::record('事务提交-done', 'notify');
			} catch (\Exception $e) {
				Db::rollback();
				Log::record('报错'.json_encode($e->getMessage()), 'notify');
				$errorMsg = $e->getMessage().' 在 '.$e->getFile().' '.$e->getLine().' 行'.$e->getTraceAsString();
				Log::error($errorMsg);

				return false;
			}

			return 'success';
		}
		if ('2' == $receivables['status']) {
			Log::record('订单'.$receivables['receipt_number'].'已经回调过了', 'notify');
		}
		Log::record('回调失败===='.json_encode($receivables), 'notify');

		return false;
	}

	/**
	 * 微信小程序扫码支付回调-订单
	 * User: wufeng
	 * Date: 2020/04/25
	 *
	 * @return bool|string
	 * @throws \think\exception\DbException
	 */
	public function ddxcxsmNotify()
	{
		$result = file_get_contents('php://input');
		Log::record('微信回调,时间'.date('Y-m-d H:i:s').'原始信息='.$result, 'notify');
		$values = json_decode(json_encode(simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		Log::record('微信回调信息===='.json_encode($values), 'notify');

		Log::record('支付单号===='.$values['out_trade_no'], 'notify');
		$receivables = ReceivablesModel::get(['receipt_number' => $values['out_trade_no']]);
		Log::record('开始===='.json_encode($receivables), 'notify');
		if ('1' == $receivables['status']) {
			Db::startTrans();
			Log::record('事务启动', 'notify');

			try {
				$this->callbackUpdate($receivables,$values,4);
				Db::commit(); // 提交事务
				Log::record('事务提交-done', 'notify');
			} catch (\Exception $e) {
				Db::rollback();
				Log::record('报错'.json_encode($e->getMessage()), 'notify');
				$errorMsg = $e->getMessage().' 在 '.$e->getFile().' '.$e->getLine().' 行'.$e->getTraceAsString();
				Log::error($errorMsg);

				return false;
			}

			return 'success';
		}
		if ('2' == $receivables['status']) {
			Log::record('订单'.$receivables['receipt_number'].'已经回调过了', 'notify');
		}
		Log::record('回调失败===='.json_encode($receivables), 'notify');

		return false;
	}

	private function callbackUpdate($receivables,$values,$type)
	{
		//缴费通过
		$contract = (new ContractModel())->get(['contract_number' => $receivables['contract_number']]);
		(new ReceivablesModel())->where(['receipt_number' => $receivables['receipt_number']])->update(['status' => 2]);
		if(1 === (int) $type || 3 === (int) $type){
			(new ContractModel())->where(['contract_number' => $receivables['contract_number']])->update(['status' => 1]);
			Log::record('全部收款成功', 'notify');
			$user_id = $values['attach'];
		}else{
			if($contract['stay_amount'] !== $receivables['amount']){
				//部分收款
				(new ContractModel())->where(['contract_number' => $receivables['contract_number']])->update(['status' => 3]);
				Log::record('部分收款成功', 'notify');
			}else{
				//全部收款
				(new ContractModel())->where(['contract_number' => $receivables['contract_number']])->update(['status' => 1]);
				Log::record('全部收款成功', 'notify');
			}
			$arr = explode(',',$values['attach']);
			$user_id = $arr[0];
		}
		Log::record('缴费成功', 'notify');
		Log::record('操作人ID===='.$user_id, 'notify');
		$parentInformation_id = (new ParentInformationModel())->get(['student_id'=>$contract['student_id']])['id'];
		$noticeTitle = '微信支付';
		$money = $values['total_fee'] / 100;
		$this->writeNotice($parentInformation_id,$user_id, $noticeTitle, '订单'.$receivables['receipt_number'].'支付成功，支付金额为'.$money,1, 3);
		Log::record('通知写入成功', 'notify');
		//更新订单状态及金额
		$amount = $values['total_fee'];//已收款金额

		/*********************财务流程**********************/
		//应收【total_amount】  项目收费【amount】  实收【net_receipts】   欠费【stay_amount】    支出【expenditure】   余额【balance】    储值【Storedvalue】
		$total_amount_money = $contract['total_amount']; //应收
		$amount_money = $contract['amount'] + $amount; //项目收费
		$storedvalue = 0;
		$net_receipts = 0;
		$des_storedvalue = 0;
		$amount_allocation = 0;//分配金额
		if($amount_money <= $total_amount_money){
			$storedvalue = 0;   //储值
			$net_receipts = $amount_money;
			$amount_allocation = $amount;
		}else if($amount_money > $total_amount_money){
			$des_storedvalue = ($amount_money - $total_amount_money); //储蓄增量
			$storedvalue = ($amount_money - $total_amount_money) + $contract['storedvalue'];
			$amount_money = $total_amount_money;
			$net_receipts = $amount_money;
			$amount_allocation = ($total_amount_money -  $contract['amount']);
		}

		$stay_amount_money = ($total_amount_money - $amount_money);  //欠费
		$expenditure_money = $contract['expenditure']; //支出[课消]
		$eduadmin_id = '';
		/********************END*****************************/
		{
			if($amount_allocation > 0){
				$checked_ids = '';
				if(4 === (int) $type){
					$arr = explode(',',$values['attach']);
					$eduadmin_id = $arr[1];
					unset($arr[0],$arr[1]);
					$checked_ids = implode(',',$arr);//资金分配
				}elseif (2 === (int) $type){
					$arr = explode(',',$values['attach']);
					unset($arr[0]);
					$checked_ids = implode(',',$arr);//资金分配
				}
				$checked_ids_arr = explode(',',$checked_ids);
				//规则：默认先把物品的钱付完
				for($h = 0; $h < count($checked_ids_arr); $h ++){
					$pos_value_arr = explode('-',$checked_ids_arr[$h]);
					if($amount_allocation > 0) {
						if ($pos_value_arr[1] == 3) {  //物品
							$res_good = (new GoodsContractModel())->get(['id' => $pos_value_arr[0]]);
							$des_good_amount = (($res_good['net_receipts'] - $res_good['assessed_amount']) - $res_good['payment']);
							if($amount_allocation >= $des_good_amount){
								$amount_allocation = $amount_allocation - $des_good_amount;
								$des_good_amount_ = $res_good['payment'] + $des_good_amount;
								$payment_balance = $res_good['payment_balance'] + $des_good_amount;
								(new GoodsContractModel())->where(['id' => $pos_value_arr[0]])->update(['payment' => $des_good_amount_, 'payment_balance' => $payment_balance]);
							}else{
								$des_good_amount_ = $res_good['payment'] + $amount_allocation;
								$payment_balance = $res_good['payment_balance'] + $amount_allocation;
								(new GoodsContractModel())->where(['id' => $pos_value_arr[0]])->update(['payment' => $des_good_amount_,'payment_balance' => $payment_balance]);
								$amount_allocation = 0;
							}
						}
					}
				}
				//分课程-分班级-求总应收金额
				if($amount_allocation > 0) {
					$net_receipts_amount_total = 0;
					for ($h = 0; $h < count($checked_ids_arr); $h++) {
						$pos_value_arr = explode('-', $checked_ids_arr[$h]);
						if ($pos_value_arr[1] == 1) {  //课程
							$res_course = (new CourseContractModel())->get(['id' => $pos_value_arr[0]]);
							$net_receipts_amount_total = $net_receipts_amount_total + ($res_course['net_receipts'] - $res_course['assessed_amount']);
						} else if ($pos_value_arr[1] == 2) {   //班级
							$res_grades = (new GradesContractModel())->get(['id' => $pos_value_arr[0]]);
							$net_receipts_amount_total = $net_receipts_amount_total + ($res_grades['net_receipts'] - $res_grades['assessed_amount']);
						}

					}


					//分配

					for ($h = 0; $h < count($checked_ids_arr); $h++) {
						$pos_value_arr = explode('-', $checked_ids_arr[$h]);
						if ($pos_value_arr[1] == 1) {  //课程
							$res_course = (new CourseContractModel())->get(['id' => $pos_value_arr[0]]);
							$rate_amount = round(($res_course['net_receipts'] / $net_receipts_amount_total) * $amount_allocation); //四舍五入取整
							//抵充欠费
							$rate_amount_total = $rate_amount;
							$contract_number = ContractModel::get(['id' => $res_course['contract_id']])['contract_number'];
							$res_info = (new StudentSubjectInfosClassModel())->where(['status' => 1, 'report_status' => 1, 'arrears_status' => 1, 'give_status' => 1, 'contract_number' => $contract_number, 'course_id' => $res_course['course_id']])->select();
							foreach ($res_info as $value){
								$info_id = $value['id'];
								if($rate_amount_total > 0) {
									if (($rate_amount_total + $value['arrears_amount']) >= 0) {
										if (!(new StudentSubjectInfosClassModel())->where(['id' => $info_id])->update(['arrears_status' => 0, 'arrears_amount' => 0])) {
											$this->error('更新课消欠费金额失败', null, '', 1);
										}
										$rate_amount_total = ($rate_amount_total + $value['arrears_amount']);
									} else {
										$value['arrears_amount'] = ($rate_amount_total + $value['arrears_amount']);
										if (!(new StudentSubjectInfosClassModel())->where(['id' => $info_id])->update(['arrears_amount' => $value['arrears_amount']])) {
											$this->error('更新课消欠费金额失败', null, '', 1);
										}
										break;
									}
								}
							}


							$rate_amount_ = $res_course['payment'] + $rate_amount;
							$payment_balance = $res_course['payment_balance'] + $rate_amount;
							(new CourseContractModel())->where(['id' => $pos_value_arr[0]])->update(['payment' => $rate_amount_, 'payment_balance' => $payment_balance]);  //更新付款金额


							//更新合同应收分配课时
							$price_ = round(((($res_course['net_receipts'] - $res_course['assessed_amount']))/($res_course['class_num'])),2); //折后应收 - 分摊金额
							$nums = round(($rate_amount / $price_),2);

							$course_paid_nums_arr = explode(',',$contract['course_paid_nums']);
							$course = explode(',',$contract['course']);
							for($l = 0; $l < count($course); $l ++){
								if($course[$l] == $res_course['course_id']){
									$course_paid_nums_arr[$l] = $course_paid_nums_arr[$l] + $nums;
									$C_Number = $contract['contract_number'];  //合同号
									$Course_Id = $res_course['course_id']; //课程ID
									$Report_Status = 1; //课程
									if((new StudentSubjectInfosClassModel())->get(['report_status' => $Report_Status, 'course_id' => $Course_Id, 'contract_number' => $C_Number])){

										(new StudentSubjectInfosClassModel())->where(['report_status' => $Report_Status, 'course_id' => $Course_Id, 'contract_number' => $C_Number])->update(['surplus_class_elimination' => $course_paid_nums_arr[$l]]);
									}
								}
							}
							$contract['course_paid_nums'] = implode(',',$course_paid_nums_arr);


						} else if ($pos_value_arr[1] == 2) {   //班级
							$res_grades = (new GradesContractModel())->get(['id' => $pos_value_arr[0]]);
							$rate_amount = round(($res_grades['net_receipts'] / $net_receipts_amount_total) * $amount_allocation); //四舍五入取整
							//抵充欠费
							$rate_amount_total = $rate_amount;
							$contract_number = ContractModel::get(['id' => $res_grades['contract_id']])['contract_number'];
							$res_info = (new StudentSubjectInfosClassModel())->where(['status' => 1, 'report_status' => 2, 'arrears_status' => 1, 'give_status' => 1, 'contract_number' => $contract_number, 'course_id' => $res_grades['course_id']])->select();
							foreach ($res_info as $value){
								$info_id = $value['id'];
								if($rate_amount_total > 0) {
									if (($rate_amount_total + $value['arrears_amount']) >= 0) {
										if (!(new StudentSubjectInfosClassModel())->where(['id' => $info_id])->update(['arrears_status' => 0, 'arrears_amount' => 0])) {
											$this->error('更新课消欠费金额失败', null, '', 1);
										}
										$rate_amount_total = ($rate_amount_total + $value['arrears_amount']);
									} else {
										$value['arrears_amount'] = ($rate_amount_total + $value['arrears_amount']);
										if (!(new StudentSubjectInfosClassModel())->where(['id' => $info_id])->update(['arrears_amount' => $value['arrears_amount']])) {
											$this->error('更新课消欠费金额失败', null, '', 1);
										}
										break;
									}
								}
							}

							$rate_amount_ = $res_grades['payment'] + $rate_amount;
							$payment_balance = $res_grades['payment_balance'] + $rate_amount;
							(new GradesContractModel())->where(['id' => $pos_value_arr[0]])->update(['payment' => $rate_amount_, 'payment_balance' => $payment_balance]); //更新付款金额

							//更新合同应收分配课时
							$price_ = round(((($res_grades['net_receipts'] - $res_grades['assessed_amount']))/($res_grades['class_num'])),2); //折后应收 - 分摊金额
							$nums = round(($rate_amount / $price_),2);

							$grades_course_paid_nums_arr = explode(',',$contract['grades_course_paid_nums']);
							$grades_course = explode(',',$contract['grades_course']);
							for($l = 0; $l < count($grades_course); $l ++){
								if($grades_course[$l] == $res_grades['course_id']){
									$grades_course_paid_nums_arr[$l] = $grades_course_paid_nums_arr[$l] + $nums;
									$C_Number = $contract['contract_number'];  //合同号
									$Course_Id = $res_grades['course_id']; //课程ID
									$Report_Status = 2; //班级
									if((new StudentSubjectInfosClassModel())->get(['report_status' => $Report_Status, 'course_id' => $Course_Id, 'contract_number' => $C_Number])){

										(new StudentSubjectInfosClassModel())->where(['report_status' => $Report_Status, 'course_id' => $Course_Id, 'contract_number' => $C_Number])->update(['surplus_class_elimination' => $grades_course_paid_nums_arr[$l]]);
									}

								}
							}

							$contract['grades_course_paid_nums'] = implode(',',$grades_course_paid_nums_arr);
						}

					}
				}


			}

		}
		//学费余额
		$payment_grades_balance = (new GradesContractModel())->where(['contract_id' => $contract['id']])->sum('payment_balance');
		$payment_course_balance = (new CourseContractModel())->where(['contract_id' => $contract['id']])->sum('payment_balance');
		$payment_money_balance = ($payment_course_balance + $payment_grades_balance); //班级与课程余额之和

		$contract_data['course_paid_nums'] = $contract['course_paid_nums'];
		$contract_data['grades_course_paid_nums'] = $contract['grades_course_paid_nums'];
		$contract_data['course_elimination'] = $contract['course_paid_nums'];
		$contract_data['grades_course_elimination'] = $contract['grades_course_paid_nums'];
		$contract_data['stay_amount']  = $stay_amount_money; //欠费
		$contract_data['amount'] = $amount_money;  //报读项目收费
		$contract_data['net_receipts'] = $net_receipts;  //实际收费
		$contract_data['total_amount'] = $total_amount_money;  //应收
		$contract_data['expenditure'] = $expenditure_money;  //课消
		$contract_data['balance'] = $payment_money_balance;  //学费余额(不包含物品费用)
		$contract_data['storedvalue'] = $storedvalue;  //储值

		$student_result = (new StudentModel())->get(['id' => $contract['student_id']]);
		//更新欠费状态
		if($contract_data['balance'] >= 0){
			(new StudentModel())->where(['id' => $contract['student_id']])->update(['arrears_status' => 1]);
		}else if($contract_data['balance'] < 0){
			(new StudentModel())->where(['id' => $contract['student_id']])->update(['arrears_status' => 0]);
		}
		Log::record('更新欠费状态', 'notify');
		//选择教务
		if($eduadmin_id != -1){
			(new StudentModel())->where(['id' => $contract['student_id']])->update(['user_edu_id' => $eduadmin_id]);
		}
		$srudent_item['storedvalue'] = $student_result['storedvalue'] + $des_storedvalue;
		(new StudentModel())->save(['storedvalue' => $srudent_item['storedvalue']],['id' => $contract['student_id']]);
		Log::record('更新学生储蓄账户', 'notify');
		if($contract_data['stay_amount'] > 0){
			$contract_data['status'] = 3;//订单状态：部分收款订单
		}else{
			$contract_data['status'] = 1;//订单状态：已收款订单
		}
		// 更新已报课程状态
		(new CourseLogModel())->save(['status' => $contract_data['status']], ['contract_number' => $contract['contract_number']]);
		Log::record('更新已报课程状态', 'notify');
		// 订单收款流水
		$operator = (new UserModel())->get($receivables['payee'])['name'];
		CommonService::writeFlowLog($contract['contract_number'], $operator,1, $amount, '记录订单收款流水',$receivables['campus_id'],$receivables['receipt_number'],$receivables['payment_method']);
		Log::record('订单收款流水', 'notify');
		//校区业绩
		$checkCampus = (new AllocationCampusModel())->get(['receipt_number'=>$receivables['receipt_number']]);
		if($checkCampus){
			(new AllocationCampusModel())->where(['receipt_number'=>$receivables['receipt_number']])->update(['status'=>2]);
			Log::record('校区业绩,待定->转正', 'notify');
		}
		//个人业绩
		$checkOnly = (new AllocationOnlyModel())->get(['receipt_number'=>$receivables['receipt_number']]);
		if($checkOnly){
			(new AllocationOnlyModel())->where(['receipt_number'=>$receivables['receipt_number']])->update(['status'=>2]);
			Log::record('个人业绩,待定->转正', 'notify');
		}
	}

	private function writeNotice($notice_object,$user_id,$notice_name,$notice_content,$flag,$notice_type)
	{
		//审批通知
		$notice = [];
		$notice['notice_time'] = date('Y-m-d H:i:s'); //通知时间
		$notice['user_id'] = $user_id; //操作审批人的id
		$notice['notice_object'] = $notice_object; //通知对象
		$notice['notice_name'] = $notice_name; //通知名称
		$notice['content'] = $notice_content; //具体内容
		$notice['notice_type'] = $notice_type; //通知方向：1机构端、家长端；2机构端；3家长端
		$notice['status'] = 1; //存稿还是发布：1发布 2存稿

		Db::name('edu_my_notice')->insert($notice);  //插入通知表
		$notice_id = Db::name('edu_my_notice')->getLastInsID();
		$_data = [];
		$notices = explode(',', $notice['notice_object']);
		foreach ($notices as &$notice) {
			$arr = [];
			$arr['notice_id'] = $notice_id;
			$arr['notice_object_id'] = $notice;
			$arr['n_type'] = $flag;
			$arr['notice_type'] = $notice_type;
			$_data[] = $arr;
		}
		Db::name('edu_my_notice_object')->insertAll($_data);
	}
}
